package com.resou.reader.mine.paycenter;

import android.util.ArrayMap;

import com.resou.reader.api.ApiImp;
import com.resou.reader.api.entry.Result;
import com.resou.reader.api.entry.UserInfoBean;
import com.resou.reader.api.entry.WXPayBean;
import com.resou.reader.api.service.PayService;
import com.resou.reader.api.service.UserService;
import com.resou.reader.base.ResouBasePresenter;
import com.resou.reader.mine.IView.UserInstance;
import com.resou.reader.paycenter.v.IPayView;
import com.resou.reader.utils.DeviceUtils;
import com.umeng.analytics.MobclickAgent;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class PayPresenter extends ResouBasePresenter<IPayView> {
    private PayService mService;
    private UserService userService;

    public PayPresenter(IPayView view) {
        super(view);
        mService = ApiImp.getInstance().getService(PayService.class);
        userService = ApiImp.getInstance().getService(UserService.class);
    }

    public void getUserInfo(String token) {
        addCompositeDisposable(
                userService.getUserInfo(token)
                        .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<Result<UserInfoBean>>() {
                            @Override
                            public void accept(Result<UserInfoBean> result) {
                                if (result.getCode() == 0 && result.getData() != null) {
                                    UserInfoBean.UBean uBean = result.getData().getU();
                                    if (uBean != null) {
                                        UserInstance.saveUserInfo(uBean);
                                        mView.sycnUserInfo();
                                    }
                                }

                            }
                        }, new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) {
                                mView.showEmpty();
                            }
                        })
        );
    }

    /**
     * 加载充值价格表
     */
    public void loadPriceList() {
        addCompositeDisposable(
                mService.rechargePrice(UserInstance.getToken())
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(listResult -> {
                            int code = listResult.getCode();
                            if (code == 0) {
                                mView.setConfigList(listResult.getData());
                            }
                        }, new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                mView.showEmpty();
                            }
                        })
        );
    }

    private static final String TAG = "PayPresenter-App";

    /**
     * 获取微信订单信息
     */
    public void fetchWXOrderInfo(int cnyPrice) {
        mView.showLoadingIndicator();
        String price = String.valueOf(cnyPrice);
        String title = "热币充值";

        mService.wxPayAndroid(UserInstance.getToken(), price, title, DeviceUtils.getIMEI(mView.getViewContext()))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Result<WXPayBean>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Result<WXPayBean> result) {
                        if (result == null) {
                            return;
                        }
                        mView.hideLoadingIndicator();
                        mView.invokeWXPay(result.getData());
                        //统计用户充值哪个金额比较多
                        Map<String, String> map = new ArrayMap<>();
                        map.put("type", title);
                        map.put("amount", price);
                        MobclickAgent.onEvent(mView.getViewContext(), "pay_amount", map);

                        map.clear();
                        map.put("充值说明", title);
                        map.put("充值金额", price);
                        MobclickAgent.onEvent(mView.getViewContext(), "pay_amount1", map);
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.hideLoadingIndicator();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 获取支付宝订单信息
     */
    public void fetchAliPayOrderInfo(int cnyPrice) {
        mView.showLoadingIndicator();
        String price = String.valueOf(cnyPrice);
        String title = "热币充值";

        String token = UserInstance.getToken();
        mService.aliPayApp(token, price)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<AliPay>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(AliPay aliPay) {
                        mView.hideLoadingIndicator();
                        mView.invokeAliPay(aliPay.getUrl());
//                        ToastUtil.makeLongToast(aliPay.getUrl());
//    //统计用户充值哪个金额比较多
////                        HashMap<String, String> map = new HashMap<>();
////                        map.put("type", title);
////                        map.put("amount", price);
////                        MobclickAgent.onEvent(mView.getViewContext(), "pay_amount", map);
////
////                        map.clear();
////                        map.put("充值说明", title);
////                        map.put("充值金额", price);
////                        MobclickAgent.onEvent(mView.getViewContext(), "pay_amount1", map);
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.showError(e);
                        mView.hideLoadingIndicator();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

}

//
//    /**
//     * 延迟查询
//     *
//     * @param timestemp 时间戳
//     * @param delayTime 延迟时间
//     */
//    public void queryRechargeRecordDelay(final long timestemp, final int delayTime) {
//        new Thread(() -> {
//            try {
//                Thread.sleep(delayTime);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            queryRechargeRecordFromServer(timestemp, delayTime);
//        }).start();
//    }
//
//    private void queryRechargeRecordFromServer(final long timestemp, final int delayTime) {
//        addCompositeDisposable(
//
//                mService.rechargeRecordList(UserInstance.getToken(), 0, "1")
//                        .subscribeOn(Schedulers.io())
//                        .observeOn(AndroidSchedulers.mainThread())
//                        .subscribe(commonDataResult -> {
//                            DLog.i(PayPresenter.class.getSimpleName(), "queryRechargeRecordFromServer success, code == " + commonDataResult.getCode());
//                            if (commonDataResult.getData() != null) {
//                                List<PayRecordBean> list = commonDataResult.getData().getData();
//                                if (list != null && list.size() > 0) {
//                                    DLog.i(PayPresenter.class.getSimpleName(), "queryRechargeRecordFromServer success, list size == " + list.size());
//                                    PayRecordBean payRecordBean = list.get(0);
//                                    if (payRecordBean.getRechargeTime() > timestemp) {
//                                        //支付成功
//                                        mView.onPaySuccess((int) payRecordBean.getRechargeAmount());
//                                    } else {
//                                        //未查询到支付结果,再尝试一次  ,共尝试3次
//                                        if (delayTime <= 500) {
//                                            queryRechargeRecordDelay(timestemp, delayTime + 500);
//                                        } else {
//                                            //支付失败
//                                            mView.onPayError("尝试了三次都没查询到 " + timestemp + "这个时间点的充值记录");
//                                        }
//                                    }
//                                    return;
//                                }
//                            }
//                            //一些不明因素，再次查询
//                            if (delayTime <= 1000) {
//                                queryRechargeRecordDelay(timestemp, delayTime + 1000);
//                            } else {
//                                //支付失败
//                                mView.onPayError("尝试了三次都没查询到 " + timestemp + "这个时间点的充值记录");
//                            }
//                        }, throwable -> {
//                            DLog.e(PayPresenter.class.getSimpleName(), "queryRechargeRecordFromServer error, msg: " + throwable.getMessage());
//                            ErrorUtils.showError(throwable);
//                            mView.onPayError(throwable.getMessage());
//                        })
//        );
//    }

